import React, {PureComponent} from "react";
import {connect} from "dva";
import {Popover} from 'antd';
// import { connect } from 'dva';
import style from "styled-components";
import {Alert, Steps, Row, Col, Modal} from "antd";
import InitialPasswordModification from "./InitialPasswordModification";
import InitialBasicInformation from "./InitialBasicInformation";
import InitialAuthenticationInformation from "./InitialAuthenticationInformation";
import InitialDepartmentalInstitutions from "./InitialDepartmentalInstitutions";
import InitialConfigure from "./InitialConfigure";
import InitialImportEmployeeBasicInformation from "./InitialImportEmployeeBasicInformation";
import InitialEnterpriseInsurance from "./InitialEnterpriseInsurance";
import InitializationCompleted from "./InitializationCompleted";
import PLoading from "../../../components/Pro/PLoading";
import {systemComInitprocessList} from "../../../services/api";

const {Step} = Steps;

@connect(state => ({
  global: state.global
}))
export default class Initialization extends PureComponent {
  state = {
    step: 0,
    cursor: 0, //企业初始化步骤
    leftInitInfo: [], //左侧初始化信息
    companyInfo: this.props.global.companyInfo, //左侧初始化信息
    dataSource: [],//初始化信息
    ifEnd: false,//是否是按照流程完成初始化。如果不是，则判断为之前已经完成过初始化流程
  };

  componentWillReceiveProps = (nextProps, newState) => {
    const {companyInfo} = {...nextProps.global};
    this.setState({companyInfo});
  };
  /******************************生命周期******************************/
  componentWillMount = () => {
    //根据后台，预设流程
    this.CurrentPage = {
      0: PLoading,
      1: InitialPasswordModification, //初始密码修改
      2: InitialBasicInformation, //完善企业基础信息
      3: InitialAuthenticationInformation, //完善企业认证信息
      4: InitialDepartmentalInstitutions, //组建部门机构
      5: InitialConfigure, //配置角色及权限
      6: InitialImportEmployeeBasicInformation, //导入员工基础信息
      7: InitialEnterpriseInsurance, //完善企业保险信息
      8: InitializationCompleted //已完成企业初始化任务
    };

    //因为后台返回的数据不一定是 0，1，2，3。。。连续的数字。
    //所以这里自定义对象迭代器。 后续可扩展给 for of 使用。
    this.CurrentPageCursor = {
      [Symbol.iterator]: () => {
        let steps = this.CurrentPage,
          stepsArr = Object.keys(steps),
          length = stepsArr.length - 1; //cursor 从0开始计算
        let index = "";
        stepsArr.find((val, key) => {
          if (val === this.state.cursor.toString()) {
            index = key;
          }
        })
        return {
          next() {
            if (index < length) {
              return {
                value: stepsArr[++index],
                done: false
              };
            } else {
              return {value: stepsArr[length], done: false};
            }
          },
          pre() {
            if (index > 1) {
              return {
                value: stepsArr[--index],
                done: false
              };
            } else {
              return {value: stepsArr[1], done: false};
            }
          }
        };
      }
    };
  };

  componentDidMount = () => {
    // this.systemComInitprocessList();
    this.init();
  };

  /******************************ajax请求******************************/
    // 查看报表详情,更新 cursor
  init = resolve => {
    systemComInitprocessList({t: "", sign: ""}).then(
      ({data = []}) => {
        console.log("查看报表详情", data);
        let {ifEnd} = this.state;
        this.setState({dataSource: data});

        //检查是否是现在完成初始化流程
        ((ifEnd) => {
          const {cursor} = this.state;
          const steps = Object.keys(this.CurrentPage);
          const length = steps.length;
          if (cursor.toString() == steps[length - 2]) {
            ifEnd = true;
            this.setState({ifEnd: true});
          }
        })(ifEnd);


        //设置游标

        this.initProcess(data);
        const result = this.completeStep(data);

        // if (result === "8" && !ifEnd) {  //之前已经完成过初始化
        //   this.props.history.push("/Organization/departmentmanagement");
        //   return;
        // }

        this.setState({cursor: result});


        if (resolve) {
          resolve(result);
        }

        // this.setState({cursor: 4});
      },
      err => {
        console.log(err);
      }
    );
  };

  initProcess = (data) => {
    let newCurrentPage = {
      0: PLoading,
    };
    data.map(val => {
      const attr = val.initProcessType;
      newCurrentPage[attr] = this.CurrentPage[attr];
    });
    newCurrentPage["8"] = InitializationCompleted;
    this.CurrentPage = {...newCurrentPage};
  };


  /******************************相关事件******************************/
    //上一步
  preStep = () => {
    const it = this.CurrentPageCursor[Symbol.iterator]();
    this.setState(pre => {
      return {cursor: it.pre().value};
    });
  };
  //下一步
  addStep = () => {
    const it = this.CurrentPageCursor[Symbol.iterator]();
    this.setState(pre => {
      return {cursor: it.next().value};
    });
  };

  //查找未完成步骤的类型
  completeStep = data => {
    //如果没有找到，则返回最后一步的设置
    if (!data.find(val => val.isComplete === "0")) {
      return "8";
    } else {
      return data.find(val => val.isComplete === "0").initProcessType;
    }
  };

  //跳转到 已完成企业初始化任务 流程
  linkLastStep = () => {
    this.setState({cursor: "8"});
  };

  //左侧初始化流程索引
  renderSteps = () => {
    {/*    <Steps
      direction="vertical"
      size="small"
      current={parseInt(cursor) - 1}
    >
      <Step title="初始密码修改"/>
      <Step title="完善企业基础信息" description=""/>
      <Step title="完善企业认证信息" description=""/>
      <Step title="组建部门机构"/>
      <Step title="配置角色及权限"/>
      <Step
        title="导入员工基础信息"
        description="赠送人脸识别+身份认证"
      />
      <Step title="完善企业保险信息"/>
      <Step title="已完成企业初始化任务"/>
    </Steps>*/
    }

    const {dataSource, cursor} = this.state;
    const length = dataSource.length;
    if (length == 0) {
      return;
    }
    const steps = dataSource.map(
      ({initProcessType_Name}, key) => (
        <Step title={initProcessType_Name} key={key}/>
      ));
    steps.push(<Step title="已完成企业初始化任务" key={length}/>);

    return (
      <Steps
        direction="vertical"
        size="small"
        current={parseInt(cursor) - 1}
      >
        {steps}
      </Steps>
    );
  }
  //提示完成初始化
  tipCompleteInit = () => {
    Modal.info({
      title: '请完善初始化信息',
      onOk() {
      },
    });
  }

  /******************************render******************************/

  render() {
    const {cursor, companyInfo} = this.state;
    const popoverTitle = "当前区域为人工干预按钮";
    const popoverContent = <div style={{padding: 10}}>仅在初始化流程出错或者快速跳出初始化流程使用 </div>;
    return (
      <Container>
        <div className="zhezhao" onClick={this.tipCompleteInit}/>
        <div className="zhezhao2" onClick={this.tipCompleteInit}/>
        <div className="Initialization">
          <div>
            <Alert
              message="由于您的企业未认证，您可以试用体验以下功能：公司管理、人事管理、行政管理、消息管理、劳务管理；通讯录仅能存储100人以内的员工；如有超出，请申请企业认证。"
              type="warning"
              showIcon
            />
          </div>
          <div style={{marginTop: 24}}>
            <Row>
              <Col span={6}>
                <div className="init-step">
                  {this.renderSteps()}
                </div>
              </Col>
              <Col span={18}>
                <div className="init-content">
                  <Popover placement="topLeft" title={popoverTitle} content={popoverContent} trigger="hover">
                    <div style={{background: "blue", color: "#fff"}}>
                      <div onClick={this.preStep}>上一步</div>
                      <div onClick={this.addStep}>下一步</div>
                      <div onClick={() => this.props.history.push("/Organization/departmentmanagement")}>跳过初始化流程</div>
                    </div>
                  </Popover>

                  {React.createElement(this.CurrentPage[cursor], {
                    companyInfo,
                    preStep: this.preStep,
                    nextStep: this.init,
                    linkLastStep: this.linkLastStep,
                    history: this.props.history
                  })}
                </div>
              </Col>
            </Row>
          </div>
        </div>

      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    padding:24px;
    overflow: auto;
    position: relative;
    .zhezhao{
    z-index: 199;
    position: fixed;
    width: 89%;
    height: 100%;
    left: 0;
    top: 0;
    cursor: not-allowed;
  }
    .zhezhao2{
    z-index: 198;
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 10%;
    cursor: not-allowed;
  }
    .Initialization{
    height: 400px;
    z-index: 200;
    position: absolute;
    right: 20px;
    left: 20px;
    .init-step{
    // width:271px;
    // border-right:1px solid #eee;
  }
    .init-content{
    padding-left:16px;
    border-left:1px solid #eee;
  }

    .ant-steps-item-wait .ant-steps-item-icon > .ant-steps-icon{
    color:#999;
  }
    .ant-steps-item-process .ant-steps-item-icon{
    background: #0F71FF;
  }

    .ant-steps-item-process > .ant-steps-item-content > .ant-steps-item-title{
    color:#333;
  }
    .ant-steps-item-process > .ant-steps-item-content > .ant-steps-item-description{
    color:#999;
  }

    .ant-steps-item-wait > .ant-steps-item-content > .ant-steps-item-title{
    color:#666;
  }
    .ant-steps-item-wait > .ant-steps-item-content > .ant-steps-item-description{
    color:#999;
  }

    .ant-steps-item-finish > .ant-steps-item-content > .ant-steps-item-title{
    color:#666;
  }
    .ant-steps-item-finish > .ant-steps-item-content > .ant-steps-item-description{
    color: #87D068;
  }

    .ant-steps-item-process > .ant-steps-item-tail:after{
    background-color: #e9e9e9;
  }
    .ant-steps-item-finish > .ant-steps-item-tail:after{
    background-color:#0F71FF
  }
    .ant-steps-item-finish .ant-steps-item-icon > .ant-steps-icon{
    color: #0F71FF;;
  }
    .ant-steps-item-finish .ant-steps-item-icon{
    border-color: #0F71FF ;
  }
  }
  }
  `;

